<template>
  <div @click="generateCaptcha" class="captcha-generator">
    <canvas ref="captchaCanvas" :width="length * 20 + 10" height="40"></canvas>
  </div>
</template>

<script>
export default {
  name: 'CaptchaGenerator',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    length: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      captchaText: ''
    }
  },
  mounted() {
    this.generateCaptcha()
  },
  methods: {
    generateCaptcha() {
      const canvas = this.$refs.captchaCanvas
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 去除容易混淆的字符
      const chars = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
      let captchaText = ''
      for (let i = 0; i < this.length; i++) {
        captchaText += chars[Math.floor(Math.random() * chars.length)]
      }

      // 绘制背景
      ctx.fillStyle = '#f8f9fa' // 浅灰色背景
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      // 绘制干扰线
      for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = this.randomColor(100, 200) // 限制颜色范围，避免过于亮或暗
        ctx.beginPath()
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.stroke()
      }

      // 绘制验证码字符
      ctx.font = '26px Arial'
      ctx.fillStyle = this.randomColor(0, 100) // 使用较深的颜色
      // 测量文本
      const rect = ctx.measureText(captchaText)
      const width = rect.width
      ctx.fillText(captchaText, (this.length * 20 + 10 - rect.width) / 2, 30)

      // 保存验证码文本，以便后续验证
      this.captchaText = captchaText
      this.$emit('update:modelValue', captchaText)
    },
    randomColor(min, max) {
      const r = Math.floor(Math.random() * (max - min) + min)
      const g = Math.floor(Math.random() * (max - min) + min)
      const b = Math.floor(Math.random() * (max - min) + min)
      return `rgb(${r},${g},${b})`
    }
  }
}
</script>

<style scoped>
.captcha-generator {
  display: inline-block;
  cursor: pointer;
  line-height: 0;
}
button {
  margin-top: 10px;
}
</style>
